import Vue from 'vue'

import ViewUI from 'view-design'

import config from './config'
import utils from './utils'
import axios from 'axios'

const http = {
	// get请求
	get: function(url, data, success, stip, etip, loading) {
		loading && ViewUI.Spin.show()
		axios.get(url, data).then((res) => {
			loading && ViewUI.Spin.hide()
			let resData = utils.getResponse(res)
			if (resData.status == 'success') {
				stip && ViewUI.Message.success('操作成功')
				success && success(resData)
			} else {
				if (etip) {
					ViewUI.Notice.error({
						title: '错误',
						desc: resData.message || '未知错误'
					})
				}
			}
		}).catch(() => {
			ViewUI.Spin.hide()
			ViewUI.Message.error('网络错误')
		})
	},
	// post请求
	post: function(url, data, success, stip, etip, loading) {
		loading && ViewUI.Spin.show()
		axios.post(url, data).then((res) => {
			loading && ViewUI.Spin.hide()
			let resData = utils.getResponse(res)
			if (resData.status == 'success') {
				stip && ViewUI.Message.success('操作成功')
				success && success(resData)
			} else {
				if (etip) {
					ViewUI.Notice.error({
						title: '错误',
						desc: resData.message || '未知错误'
					})
				}
			}
		}).catch((e) => {
			ViewUI.Spin.hide()
			ViewUI.Message.error('网络错误')
		})
	},
	// post下载文件
	downloadFile: function(url, data, name) {
		ViewUI.Spin.show()
		axios.post(url, data, {
			responseType: 'blob'
		}).then((res) => {
			ViewUI.Spin.hide()
			if (res.status == 200) {
				let blob = new Blob([res.data], {
					type: res.data.type
				})
				let downloadElement = document.createElement('a')
				let href = window.URL.createObjectURL(blob)
				downloadElement.href = href
				downloadElement.download = name || "default"
				downloadElement.style.display = 'none'
				document.body.appendChild(downloadElement)
				downloadElement.click()
				window.URL.revokeObjectURL(href)
				document.body.removeChild(downloadElement)
			}
		}).catch((e) => {
			ViewUI.Spin.hide()
			ViewUI.Message.error('请求失败')
		})
	},
	// get下载显示图片
	downloadImage: function(url, data, success) {
		ViewUI.Spin.show()
		axios.post(url, data, {
			responseType: 'arraybuffer'
		}).then((res) => {
			ViewUI.Spin.hide()
			if (res.status == 200) {
				let base64 = 'data:image/png;base64,' + btoa(
					new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
				)
				success(base64)
			}
		}).catch((e) => {
			ViewUI.Spin.hide()
			ViewUI.Message.error('请求失败')
		})
	},
}

Vue.prototype.$request = http

export default http
